<template>
  <div class="login-container">

    <div class="login-form" v-show="canvasShow">
      <h3>基于人脸识别的家谱管理系统</h3>
      <p class="titleInfo">请把正脸对准摄像头</p>
      <div class="regInfo">
        <!-- <div class="tip">没有检测到脸</div> -->
        <div class="canvas">

          <!--描绘video截图-->
          <canvas ref="cav" id="canvas" width="200" height="200"></canvas>
          <!--video用于显示媒体设备的视频流，自动播放-->
          <video ref="vd" id="video" autoplay playsinline style="width: 200px;height: 200px"></video>
        </div>
      </div>
<!--      <p style="text-align:center;padding:50px 0 0">-->
<!--        <el-button @click="drawImage" icon="el-icon-camera" size="small">拍照</el-button>      </p>-->
      <p style="text-align:center;padding:50px 0 0">
        <el-button id="capture" ref="capture" @click='handleClick'>登录</el-button>
      </p>
      <!-- <img :src='imgUrl' width="100" height="100"> -->
    </div>
    <div v-show="tipShow" class="tipShow">
      <el-alert
        title="验证成功"
        type="success"
        center
        :closable="false"
        show-icon>
      </el-alert>
    </div>
    <div v-show="errorShow" class="tipShow">
      <el-alert
        title="验证失败"
        type="error"
        center
        :closable="false"
        show-icon>
      </el-alert>
    </div>
  </div>

</template>

<script>
import {checkFace,loginByFace} from '@/api/loginByFace'
import axios from 'axios'
import {uploadUserFace} from "@/api/system/user";


export default {
  components: {},
  name: "LoginByFace",
  data() {
    return {
      code: '',
      imgUrl: '',
      formData: {},
      vdstate: false,
      states: false,
      canvasShow: true,
      tipShow: false,
      errorShow: false,
      loginForm: {
        username: '',
        password: '',
      }
    }
  },
  methods: {
    /*调用摄像头拍照开始*/
    onTake() {
      this.visible = true;
      this.getCompetence();
    },
    // 调用摄像头权限
    getCompetence() {
      //必须在model中render后才可获取到dom节点,直接获取无法获取到model中的dom节点
      this.$nextTick(() => {
        const _this = this;
        this.os = false; //切换成关闭摄像头
        this.thisCancas = document.getElementById("canvasCamera");
        this.thisContext = this.thisCancas.getContext("2d");
        this.thisVideo = document.getElementById("videoCamera");
        // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
        // 使用getUserMedia，因为它会覆盖现有的属性。
        // 这里，如果缺少getUserMedia属性，就添加它。
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            // 首先获取现存的getUserMedia(如果存在)
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            // 有些浏览器不支持，会返回错误信息
            // 保持接口一致
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: _this.videoWidth,
            height: _this.videoHeight,
            transform: "scaleX(-1)"
          }
        };
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in _this.thisVideo) {
              _this.thisVideo.srcObject = stream;
            } else {
              // 避免在新的浏览器中使用它，因为它正在被弃用。
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function (e) {
              _this.thisVideo.play();
            };
          })
          .catch(err => {
            this.$notify({
              title: "警告",
              message: "没有开启摄像头权限或浏览器版本不兼容.",
              type: "warning"
            });
          });
      });
    },
    //绘制图片
    drawImage() {
      // 点击，canvas画图
      this.thisContext.drawImage(
        this.thisVideo,
        0,
        0,
        this.videoWidth,
        this.videoHeight
      );
      // 获取图片base64链接
      this.imgSrc = this.thisCancas.toDataURL();
      /*const imgSrc=this.imgSrc;*/
    },
    // handleClick() {
    //   let _this = this
    //
    //   if (!this.vdstate) {
    //     return false
    //   }
    //   if (!_this.states) {
    //     // 注册拍照按钮的单击事件
    //
    //     let video = this.$refs['vd']
    //     let canvas = this.$refs['cav']
    //     console.log(canvas);
    //     // let form = this.$refs["myForm"];
    //     let context = canvas.getContext('2d')
    //     // 绘制画面
    //     context.drawImage(video, 0, 0, 200, 200)
    //     let base64Data = canvas.toDataURL('image/jpg')
    //
    //     // 封装blob对象
    //     let blob = this.dataURItoBlob(base64Data, 'camera.jpg') // base64 转图片file
    //     let formData = new FormData()
    //     formData.append('file', blob)
    //
    //     this.imgUrl = base64Data
    //
    //     // loginByFace(formData).then(res => {
    //     //   console.log(res.status == 200)
    //     //   if (res.status == 200) {
    //     //     axios({
    //     //       method: 'post',
    //     //       url: '/loginByFace',
    //     //       data: formData
    //     //     }).then(function (response) {
    //     //       console.log(response)
    //     //       _this.states = true
    //     //       _this.canvasShow = false
    //     //       if (response.status == 200) {
    //     //         _this.tipShow = true
    //     //         //和登陆成功同样逻辑
    //     //         _this.$store.commit('init_currentUser', resp.obj);
    //     //         window.sessionStorage.setItem("user", JSON.stringify(resp.obj));
    //     //         let path = _this.$route.query.redirect;
    //     //         //console.log(path);
    //     //         _this.$router.replace((path == "/" || path == undefined) ? '/home' : path);
    //     //         //this.$router.replace("/home");//replace方法不会回退到上个页面 push则会回到上个页面
    //     //       } else {
    //     //         _this.errorShow = true
    //     //       }
    //     //       _this.$message.success('验证通过' + '!')
    //     //     })
    //     //       .catch(function (error) {
    //     //         console.log(error)
    //     //       })
    //     //   } else {
    //     //     return false
    //     //   }
    //     // })
    //   }
    //
    // },
    handleClick() {
        let _this = this

        if (!this.vdstate) {
          return false
        }
        if (!_this.states) {
          // 注册拍照按钮的单击事件

          let video = this.$refs['vd']
          let canvas = this.$refs['cav']
          console.log(canvas);
          // let form = this.$refs["myForm"];
          let context = canvas.getContext('2d')
          // 绘制画面
          context.drawImage(video, 0, 0, 200, 200)
          let base64Data = canvas.toDataURL('image/jpg')

          // 封装blob对象
          let blob = this.dataURItoBlob(base64Data, 'camera.jpg') // base64 转图片file
          let formData = new FormData()
          formData.append('file', blob)

          this.imgSrc = base64Data
        }
      if (this.imgSrc != undefined) {
        this.fileName = this.imgSrc;
        const fileName = this.fileName.substring(this.fileName.indexOf(",") + 1)
        let data = {
          file: fileName
        };
        //这里是图片的格式为base64的，所以需要把前面的 data:image/png;base64,去掉，前端可以截取掉，后台也可以，商量一下
        // const fileName=this.fileName.substring(this.fileName.indexOf(",")+1)
        loginByFace(data).then(res => {
          this.$message({
            message: "登录成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.visible = false;
              this.$emit("refreshDataList");
            }
          });
          this.$router.push({ path: this.redirect || "/index" }).catch(()=>{});

          //我这里返回的状态成功是00，这里是需要看你们后台返回什么
          if (res.status.code == "200") {
            this.$router.push({ path: this.redirect || "/index" }).catch(()=>{});
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.visible = false;
                this.$emit("refreshDataList");
              }
            });
          } else {
            this.$message.error(res.status.errorMessage);
          }
        })
      } else {
        this.$message.error("请先拍照上传");
      }
    },
    dataURItoBlob(base64Data) {
      var byteString
      if (base64Data.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(base64Data.split(',')[1])
      else byteString = unescape(base64Data.split(',')[1])
      var mimeString = base64Data
        .split(',')[0]
        .split(':')[1]
        .split(';')[0]
      var ia = new Uint8Array(byteString.length)
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ia], {type: mimeString})
    }
  },
  created() {
    var _this = this
    let a = JSON.stringify(navigator);
    // console.log(this.$route.query.code)
    // this.handlecode()
    this.$nextTick(() => {
      var _this = this
      // console.log('video', this.$refs['vd'])
      // return
      // 访问用户媒体设备的兼容方法
      function getUserMedia(constrains, success, error) {
        var video = _this.$refs['vd'];
        if (navigator.mediaDevices.getUserMedia) {
          // 最新标准API
          let myCons = {...constrains, video: true}
          navigator.mediaDevices
            .getUserMedia(constrains)
            .then((stream) => {
              video.srcObject = stream
              video.play();
              _this.vdstate = true
            })
            .catch(error)
        } else if (navigator.webkitGetUserMedia) {
          // webkit内核浏览器
          navigator
            .webkitGetUserMedia(constrains)
            .then(success)
            .catch(error)
        } else if (navigator.mozGetUserMedia) {
          // Firefox浏览器
          navagator
            .mozGetUserMedia(constrains)
            .then(success)
            .catch(error)
        } else if (navigator.getUserMedia) {
          // 旧版API
          navigator
            .getUserMedia(constrains)
            .then(success)
            .catch(error)
        }
      }

      var video = this.$refs['vd']
      var canvas = this.$refs['cav']
      // debugger
      var context = canvas.getContext('2d')

      // 成功的回调函数
      function success(stream) {
        _this.vdstate = true
        // 兼容webkit内核浏览器
        var CompatibleURL = window.URL || window.webkitURL
        // 将视频流设置为video元素的源
        video.src = CompatibleURL.createObjectURL(stream)
        // 播放视频
        video.play()
      }

      // 异常的回调函数
      function error(error) {
        alert(error)
        console.log('访问用户媒体设备失败：', error.name, error.message)
      }

      if (
        navigator.mediaDevices.getUserMedia ||
        navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia
      ) {
        // 调用用户媒体设备，访问摄像头
        getUserMedia(
          {
            video: {width: 200, height: 200}
          },
          success,
          error
        )
      } else {
        alert('你的浏览器不支持访问用户媒体设备')
      }
      // 获取图片
    })
  },
  mounted: function () {
    //setInterval(this.handleClick, 3000)
  },
  // 组件更新
  updated: function () {
  }
}
</script>


<style rel="stylesheet/scss" lang="scss" scoped>

.el-alert__title, .el-alert__icon {
  font-size: 20px;
}

.regInfo {
  width: 200px;
  height: 200px;
  overflow: hidden;
  border: 1px solid #ccc;
  border-radius: 50%;
  margin: 0 auto;
  position: relative;

  .tip {
    position: absolute;
    top: 0;
    width: 100%;
    height: 40px;
    line-height: 40px;
    background: rgba(0, 0, 0, 0.2);
    text-align: center;
  }

  .canvas {
    position: absolute;
    top: 0;
    width: 100%;
  }
}

.titleInfo {
  text-align: center;
  font-weight: 700;
  padding: 30px 0 20px;
}

.tipShow {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 180px;
  margin-left: -90px;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
</style>
